<template>
  <div>
    <yt-crud
      ref="crudRef"
      :data="data"
      :table-props="{
        delBtn: false,
        menuSlot: true,
        menuWidth: 270,
        selection: false,
      }"
      :form-props="{
        width: 800,
      }"
      :loading="state.loading"
      :total="state.total"
      v-model:page="state.page"
      v-model:query="state.query"
      @on-load="getData"
      @saveFun="onSave"
      @del-fun="handleDelete"
      @openBeforeFun="handleOpenBefore"
      :column="column"
    >
      <template #state="scope">
        <el-switch
          v-model="scope.row.state"
          active-value="running"
          inactive-value="stopped"
          disabled
          style="--el-switch-on-color: #029D40; --el-switch-off-color: #DFDFDF"
        />
      </template>
      <template #xf="scope">
        <el-button icon="Pointer" size="small" type="primary" plain @click="handleIssue(scope.row)">下发</el-button>
      </template>
      <template #log="scope">
        <el-button size="small" type="primary" @click="handleViewLog(scope.row.id)">查看</el-button>
      </template>
      <template #menuSlot="scope">
        <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
          <el-popconfirm title="确认要删除？" @confirm="handleDelete(scope.row)" class="mg-left-10">
            <template #reference>
              <el-button :disabled="scope.row.state == 'running'" link type="danger" icon="Delete" />
            </template>
          </el-popconfirm>
        </el-tooltip>
        <el-divider direction="vertical" />
        <el-tooltip v-if="scope.row.state === 'running'" class="box-item" effect="dark" content="停止" placement="top">
          <el-button link type="danger" icon="Close" @click="handleStop(scope.row)" />
        </el-tooltip>
        <el-tooltip v-else-if="scope.row.state === 'stopped'" class="box-item" effect="dark" content="开启" placement="top">
          <el-button link type="success" icon="Open" @click="handleOpen(scope.row)" />
        </el-tooltip>
        <el-tooltip v-else-if="scope.row.state === 'finished'" class="box-item" effect="dark" content="重新启动" placement="top">
          <el-button link type="success" icon="Refresh" @click="handleReload(scope.row)" />
        </el-tooltip>
      </template>
      <template #hourFormItem>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="小时">
              <el-select v-model="selectedHours" multiple clearable placeholder="请选择小时" style="width: 100%" @change="handleTimeChange">
                <el-option v-for="hour in 24" :key="hour-1" :label="hour-1" :value="hour-1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分钟">
              <el-select v-model="selectedMinutes" multiple clearable placeholder="请选择分钟" style="width: 100%" @change="handleTimeChange">
                <el-option v-for="minute in 60" :key="minute-1" :label="minute-1" :value="minute-1" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template #daysFormItem>
        <el-form-item label="模式">
          <el-radio-group v-model="dayType" @change="handleDayTypeChange">
            <el-radio label="everyday">每天</el-radio>
            <el-radio label="workday">工作日</el-radio>
            <el-radio label="specific">指定</el-radio>
          </el-radio-group>

          <el-select v-if="dayType === 'specific'" v-model="selectedDays" placeholder="可多选" multiple style="width: 100%" @change="handleDaysChange">
            <el-option v-for="(item, index) of weekDays" :key="index" :label="item.value" :value="String(item.key)">{{ item.value }}</el-option>
          </el-select>
        </el-form-item>
      </template>
      <template #actionForm="{ row }">
        <optput style="width: 100%;" v-model:list="row.actions" actions="device, group" />
      </template>
    </yt-crud>
    <log-dialog ref="logDialogRef" type="task" />
  </div>
</template>

<script lang="ts" setup>
import { IColumn } from '@/components/common/types/tableCommon'
import { getTaskList, saveTask, stopTask, reloadTask, startTask, deleteTask, issueTask } from './api/scheduledTask.api'

import LogDialog from './modules/logDialog.vue'
import YtCrud from '@/components/common/yt-crud.vue'
import optput from './ruleSys/modules/output.vue'

// 查看日志
const logDialogRef = ref()
const handleViewLog = (id: string) => {
  logDialogRef.value.openDialog(id)
}

const column: IColumn[] = [
  {
    label: '下发',
    key: 'xf',
    slot: true,
    formHide: true,
    align: 'center',
    tableWidth: 100,
  },
  {
    label: '任务名称',
    key: 'name',
    rules: [{ required: true, message: '任务名称不能为空' }],
  },
  {
    label: '状态',
    key: 'state',
    slot: true,
    formHide: true,
  },
  {
    label: '任务类型',
    key: 'type',
    type: 'radio',
    formHide: true,
    componentProps: {
      defaultValue: 'timer',
      options: [
        {
          label: '定时执行',
          value: 'timer',
        },
      ],
    },
    rules: [{ required: true, message: '任务类型不能为空' }],
  },
  {
    label: '小时',
    key: 'hour',
    formItemSlot: true,
    hide: true,
    rules: [{ required: true, message: '小时不能为空' }],
  },
  {
    label: '分钟',
    key: 'minute',
    formItemSlot: true,
    hide: true,
    rules: [{ required: true, message: '分钟不能为空' }],
  },
  {
    label: '天数',
    key: 'days',
    formItemSlot: true,
    hide: true,
    rules: [{ required: true, message: '天数不能为空' }],
  },
  {
    label: '执行动作',
    key: 'action',
    hide: true,
    formSlot: true,
  },
  {
    label: '执行日志',
    key: 'log',
    slot: true,
    formHide: true,
  },
  {
    label: '任务描述',
    key: 'desc',
    hide: true,
    componentProps: {
      type: 'textarea',
      row: 3,
    },
  }
]

const data = ref()
const selectedHours = ref<number[]>([])
const selectedMinutes = ref<number[]>([])
const dayType = ref('everyday')
const selectedDays = ref<string[]>([])
const currentExpression = ref('')

const weekDays = [
  { value: '星期一', key: 2 },
  { value: '星期二', key: 3 },
  { value: '星期三', key: 4 },
  { value: '星期四', key: 5 },
  { value: '星期五', key: 6 },
  { value: '星期六', key: 7 },
  { value: '星期日', key: 1 },
]

// 处理时间变化
const handleTimeChange = () => {
  currentExpression.value = generateCronExpression()
}

// 处理天数类型变化
const handleDayTypeChange = () => {
  if (dayType.value === 'workday') {
    selectedDays.value = ['2', '3', '4', '5', '6']
  } else if (dayType.value === 'everyday') {
    selectedDays.value = []
  } else if (dayType.value === 'specific') {
    selectedDays.value = []
  }
  currentExpression.value = generateCronExpression()
}

// 处理具体天数变化
const handleDaysChange = () => {
  currentExpression.value = generateCronExpression()
}

// 生成cron表达式
const generateCronExpression = () => {
  if (selectedHours.value.length === 0 || selectedMinutes.value.length === 0) {
    return ''
  }

  // 对小时和分钟进行排序，确保表达式格式一致
  const hours = selectedHours.value.sort((a, b) => a - b).join(',')
  const minutes = selectedMinutes.value.sort((a, b) => a - b).join(',')
  
  // 初始化日期和星期的值
  let dayOfMonth = '*'
  let dayOfWeek = '?'

  // 根据选择的天数类型设置相应的值
  if (dayType.value === 'workday') {
    dayOfMonth = '?'  // 使用星期时，日期必须是 ?
    dayOfWeek = '2-6'  // 工作日对应周一到周五（2-6）
  } else if (dayType.value === 'specific' && selectedDays.value.length > 0) {
    dayOfMonth = '?'  // 使用星期时，日期必须是 ?
    dayOfWeek = selectedDays.value.join(',')
  } else if (dayType.value === 'everyday') {
    dayOfMonth = '*'  // 每天使用 *
    dayOfWeek = '?'   // 使用日期时，星期必须是 ?
  }

  // 秒固定为 0，月份使用 *，年份省略
  return `0 ${minutes} ${hours} ${dayOfMonth} * ${dayOfWeek}`
}

const handleDelete = (row) => {
  state.loading = true
  deleteTask(row.id)
    .then(() => {
      ElMessage.success('删除成功!')
      getData()
    })
    .finally(() => {
      state.loading = false
    })
}

const state = reactive({
  page: {
    pageSize: 10,
    pageNum: 1,
  },
  total: 0,
  loading: false,
  query: {},
})

// 修改保存数据的函数
const onSave = ({ type, data, cancel }: any) => {
  console.log('onSave', type, data)
  
  // 验证必填项
  if (selectedMinutes.value.length === 0) {
    ElMessage.error('请选择分钟')
    state.loading = false
    return
  }
  if (selectedHours.value.length === 0) {
    ElMessage.error('请选择小时')
    state.loading = false
    return
  }
  if (dayType.value === 'specific' && selectedDays.value.length === 0) {
    ElMessage.error('请选择具体天数')
    state.loading = false
    return
  }

  state.loading = true
  // 生成最新的表达式
  currentExpression.value = generateCronExpression()

  saveTask({
    ...toRaw(data),
    actions: toRaw(data).actions.map((m) => ({
      config: JSON.stringify(m),
      type: m.type,
    })),
    expression: currentExpression.value,
  })
  .then(() => {
    ElMessage.success(type === 'add' ? '添加成功' : '编辑成功')
    cancel()
    getData()
  })
  .finally(() => {
    state.loading = false
  })
}

// 修改事件处理函数
const handleOpenBefore = (params) => {
  console.log('弹窗打开前的数据', params);
  const { type, data } = params;
  if (type === 'add') {
    console.log('新增表单初始化');
    // 新增时设置默认值
    selectedHours.value = []
    selectedMinutes.value = []
    dayType.value = 'everyday'
    selectedDays.value = []
    currentExpression.value = ''
    
    // 确保actions为空数组
    if (!data.actions) {
      data.actions = []
    }
  } else if (type === 'update') {
    console.log('编辑表单初始化', data);
    // 编辑时解析现有表达式并回显
    if (data?.expression) {
      parseCronExpression(data.expression)
      currentExpression.value = data.expression
    }
    
    // 处理actions数据
    if (data.actions && Array.isArray(data.actions)) {
      // 转换actions数据结构
      data.actions = data.actions.map(action => {
        // 如果action.config是字符串，需要解析为对象
        if (action.config && typeof action.config === 'string') {
          const configObj = JSON.parse(action.config)
          return {
            ...configObj,
            type: action.type
          }
        }
        return action
      })
    } else {
      data.actions = []
    }
  }
}

const handleIssue = (row) => {
  state.loading = true
  issueTask(row.id).then((res) => {
    if (res.data) {
      getData()
      ElMessage.success('下发成功')
      return
    }
    ElMessage.error(res.message)
  })
  .finally(() => {
    state.loading = false
  })
}

// 重启
const handleReload = (row) => {
  state.loading = true
  reloadTask(row.id)
    .then((res) => {
      if (res.data) {
        getData()
        ElMessage.success('重启成功')
        return
      }
      ElMessage.error(res.message)
    })
    .finally(() => {
      state.loading = false
    })
}

// 打开
const handleOpen = (row) => {
  state.loading = true
  startTask(row.id)
    .then((res) => {
      if (res.data) {
        getData()
        ElMessage.success('开启成功')
        return
      }
      ElMessage.error(res.message)
    })
    .finally(() => {
      state.loading = false
    })
}

// 停止
const handleStop = (row) => {
  state.loading = true
  stopTask(row.id)
    .then((res) => {
      if (res.data) {
        getData()
        ElMessage.success('停止成功')
        return
      }
      ElMessage.error(res.message)
    })
    .finally(() => {
      state.loading = false
    })
}

const getData = () => {
  state.loading = true
  getTaskList({
    ...state.page,
  }).then((res) => {
    data.value = res.data.rows
    state.total = res.data.total
  })
  state.loading = false
}

// 解析cron表达式并设置表单值
const parseCronExpression = (expression: string) => {
  if (!expression) return

  const parts = expression.split(' ')
  if (parts.length >= 6) {
    // 解析分钟 (parts[1])
    selectedMinutes.value = parts[1] === '*' ? [] : parts[1].split(',').map(Number)

    // 解析小时 (parts[2])
    selectedHours.value = parts[2] === '*' ? [] : parts[2].split(',').map(Number)

    // 解析天数 (parts[3]和parts[5])
    if (parts[5] === '2-6') {
      // 工作日
      dayType.value = 'workday'
      selectedDays.value = ['2', '3', '4', '5', '6']
    } else if (parts[5] === '?' && parts[3] === '*') {
      // 每天
      dayType.value = 'everyday'
      selectedDays.value = []
    } else if (parts[5] !== '?' && parts[5] !== '*') {
      // 指定天数
      dayType.value = 'specific'
      selectedDays.value = parts[5].split(',').map(String)
    }
  }
}
</script>

<style scoped>
</style>